package org.gnu.williamjoy.cellular.view;

import org.gnu.williamjoy.cellular.CellularGrid;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import android.view.View;

public class CellGridView extends View implements Runnable {

    private CellularGrid cellularGrid;
    private Paint paint;
    private int cellSize;

    public CellGridView(Context context) {
        super(context);
        this.cellSize = 4;
        this.cellularGrid = null;
        this.paint = new Paint();
        paint.setAntiAlias(true);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        super.onDraw(canvas);

        if (this.cellularGrid != null) {
            this.paint.setColor(0xFFA80091);
            for (int i = 0; i < cellularGrid.getWidth(); i++) {
                for (int j = 0; j < cellularGrid.getHeight(); j++) {
                    if (cellularGrid.isAlive(i, j))
                        canvas.drawRect(i * cellSize, j * cellSize, (i + 1)
                                * cellSize, (j + 1) * cellSize, paint);
                }
            }
            paint.setColor(Color.WHITE);
            canvas.drawText("total cell:" + this.cellularGrid.getTotal(), 0,
                    10, paint);
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (hasFocus) {
            if (null == this.cellularGrid) {
                this.cellularGrid = new CellularGrid(
                        this.getWidth() / cellSize, this.getHeight() / cellSize);

                this.cellularGrid.shuffle();
                new Thread(this).start();
            }
        }
    }

    public void shuffle() {
        if (this.cellularGrid != null) {
            cellularGrid.shuffle();
        }
    }

    public void bounce() {
        if (this.cellularGrid != null) {
            cellularGrid.bounce();
        }
    }

    @Override
    public void run() {
        while (true) {
            if (this.cellularGrid != null) {
                cellularGrid.step();
                this.postInvalidate();
            } else {
                Thread.yield();
            }
            try {
                Thread.sleep(800);
            } catch (InterruptedException e) {
                Log.d("UpdatingThread", e.toString());
            }
        }
    }
}
